import { Resource } from '../../resources/types';
import { Promotion } from './PromotionService';
import { API_PATHS } from '../../../config/apiConfig';

const API_BASE = API_PATHS.promotionResources;

export interface PromotionResource {
  id: string;
  promotionId: string;
  resourceId: string;
  createdAt: string;
  updatedAt: string;
  promotion?: Promotion;
  resource?: Resource;
}

export class PromotionResourceService {
  private static getHeaders(includeAuth: boolean = true) {
    const headers: Record<string, string> = {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    };

    if (includeAuth) {
      const token = localStorage.getItem('token');
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }
    }

    return headers;
  }

  static async createPromotionResource(promotionId: string, resourceId: string): Promise<PromotionResource> {
    const response = await fetch(`${API_BASE}`, {
      method: 'POST',
      headers: this.getHeaders(),
      body: JSON.stringify({
        promotionId,
        resourceId
      })
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '创建促销活动与资源关联失败');
    }

    return response.json();
  }

  static async getPromotionResources(promotionId: string): Promise<Resource[]> {
    const response = await fetch(`${API_BASE}/promotion/${promotionId}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取促销活动关联的资源失败');
    }

    const data = await response.json();
    console.log('API原始返回数据:', data);
    // 检查返回的数据结构，如果有records字段，则返回records数组
    return data.records || data;
  }

  static async getResourcePromotions(resourceId: string): Promise<Promotion[]> {
    console.log('调用getResourcePromotions, resourceId:', resourceId);
    const response = await fetch(`${API_BASE}/resource/${resourceId}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取资源关联的促销活动失败');
    }

    const data = await response.json();
    console.log('getResourcePromotions API返回数据:', data);
    
    // 处理返回的数据
    let promotions: any[] = [];
    
    // 检查返回的数据结构
    if (Array.isArray(data)) {
      console.log('返回数据是数组');
      promotions = data;
    } else if (data.records && Array.isArray(data.records)) {
      console.log('返回数据包含records数组');
      promotions = data.records;
    } else if (data.data && Array.isArray(data.data)) {
      console.log('返回数据包含data数组');
      promotions = data.data;
    } else {
      console.log('返回数据结构不符合预期，尝试直接返回');
      promotions = Array.isArray(data) ? data : [data];
    }

    // 确保每个促销活动对象都有promotionId字段
    return promotions.map(promotion => {
      // 如果promotion本身就有promotionId字段，直接使用
      if (promotion.promotionId) {
        console.log(`促销活动 ${promotion.id} 已有promotionId: ${promotion.promotionId}`);
        return promotion;
      }
      
      // 如果promotion没有promotionId字段，但有id字段，将id赋值给promotionId
      if (promotion.id) {
        console.log(`促销活动 ${promotion.id} 没有promotionId字段，使用id: ${promotion.id}`);
        return {
          ...promotion,
          promotionId: promotion.id
        };
      }
      
      // 如果既没有promotionId也没有id，记录错误并返回原对象
      console.error('促销活动对象既没有promotionId也没有id字段:', promotion);
      return promotion;
    });
  }

  static async deletePromotionResource(relationId: string): Promise<void> {
    const response = await fetch(`${API_BASE}/${relationId}`, {
      method: 'DELETE',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '删除促销活动与资源的关联失败');
    }
  }

  static async deleteByPromotionId(promotionId: string): Promise<void> {
    const response = await fetch(`${API_BASE}/promotion/${promotionId}`, {
      method: 'DELETE',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '删除促销活动的所有资源关联失败');
    }
  }

  static async deleteByResourceId(resourceId: string): Promise<void> {
    const response = await fetch(`${API_BASE}/resource/${resourceId}`, {
      method: 'DELETE',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '删除资源的所有促销活动关联失败');
    }
  }
}